package com.jen.queue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DelayedMessageQueueConfig
 * @Description 延时消息队列配置
 * @Date 2021/12/17 11:16
 * @Author Rick Jen
 */
@Configuration
@Slf4j
public class DelayedMessageQueueConfig {

    /**
     * 逾期延时队列
     */
    public final static String DELAYED_QUEUE = "delayed_queue";

    /**
     * 新生队列
     */
    public final static String NEWLY_BORN_QUEUE = "newly_born_queue";

    /**
     * 延时交换机
     */
    public final static String DELAYED_EXCHANGE = "delayed_exchange";


    /**
     * 延时路由key
     */
    public final static String DELAYED_ROUTING_KEY = "delayed_routing_key";

    /**
     * rabbitmq延时消息最大延时 毫秒
     */
    public final static Long MAX_EXPIRE = 4294967295L;

    /**
     * 创建延时队列
     */
    @Bean
    public Queue delayQueue() {
        log.info("创建延时队列:{}", DELAYED_QUEUE);
        Map<String, Object> map = new HashMap<>();
        // 把一个队列修改为延迟队列
        // 消息的最大存活时间 单位为毫秒（最大延时4294967295毫秒）  一天86400秒
        map.put("x-message-ttl", MAX_EXPIRE);
        // 该队列里面的消息死了，去哪个交换机
        map.put("x-dead-letter-exchange", DELAYED_EXCHANGE);
        // 该队列里面的消息死了，去那个交换机，由哪个路由 key 来路由他
        map.put("x-dead-letter-routing-key", DELAYED_ROUTING_KEY);
        return new Queue(DELAYED_QUEUE, true, false, false, map);
    }


    /**
     * 延时交换机
     */
    @Bean
    public DirectExchange delayedExchange() {
        log.info("创建延时交换机:{}", DELAYED_EXCHANGE);
        return new DirectExchange(DELAYED_EXCHANGE);
    }

    /**
     * 新生队列
     */
    @Bean
    public Queue newlyBornQueue() {
        log.info("创建新生队列:{}", NEWLY_BORN_QUEUE);
        return new Queue(NEWLY_BORN_QUEUE);
    }

    /**
     * 绑定
     */
    @Bean
    public Binding bindingQueue() {
        log.info("通过路由Key：{}，将队列：{}，绑定到延时交换机：{}上", DELAYED_ROUTING_KEY, NEWLY_BORN_QUEUE, DELAYED_EXCHANGE);
        return BindingBuilder.bind(newlyBornQueue()).to(delayedExchange()).with(DELAYED_ROUTING_KEY);
    }
}
